#!/bin/bash

# 完成后手动操作：
# 1、root不允许远程登录
# 2、虚拟机重启测试（磁盘自动挂载、mysql自启动）

# 脚本功能：自动部署mysql5.7
# 本脚本地址: https://gitee.com/jaken150/centos-mysql-bash/raw/master/install-mysql-single.sh
# 测试系统：CentOS7.9
# mysql安装文件：二进制包
# mysql5.6下载地址1：https://mirrors.aliyun.com/mysql/MySQL-5.6/mysql-5.6.51-linux-glibc2.12-x86_64.tar.gz
# mysql5.6下载地址1：https://jaken150-1255922873.cos.ap-nanjing.myqcloud.com/mysql-5.6.51-linux-glibc2.12-x86_64.tar.gz

# mysql5.7下载地址1：https://downloads.mysql.com/archives/get/p/23/file/mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz
# mysql5.7下载地址2：https://jaken150-1255922873.cos.ap-nanjing.myqcloud.com/mysql-5.7.44-linux-glibc2.12-x86_64.tar.gz

# mysql8.0.20 下载地址：https://jaken150-1255922873.cos.ap-nanjing.myqcloud.com/mysql-8.0.20-linux-glibc2.12-x86_64.tar.xz
# mysql8.0.33 下载地址：https://jaken150-1255922873.cos.ap-nanjing.myqcloud.com/mysql-8.0.33-linux-glibc2.12-x86_64.tar.xz


# mysql Router 下载地址：https://dev.mysql.com/downloads/file/?id=526077
# 或者官网下载
# 将本脚本和二进制包放在同一目录下脚本会在本目录下创建mysql作为mysql安装目录
# 官方安详说明 https://dev.mysql.com/doc/refman/5.7/en/binary-installation.html
# 主从配置优化 参考：https://www.jianshu.com/p/edd2e20aeaee

# 带格式的echo函数
function echo_info() {
    echo -e "[\033[36m$(date +%T)\033[0m] [\033[32mINFO\033[0m] \033[37m$@\033[0m"
}
function echo_warning() {
    echo -e "[\033[36m$(date +%T)\033[0m] [\033[1;33mWARNING\033[0m] \033[1;37m$@\033[0m"
}
function echo_error() {
    echo -e "[\033[36m$(date +%T)\033[0m] [\033[41mERROR\033[0m] \033[1;31m$@\033[0m"
}

# 生成中等强度的MySQL密码
generate_mysql_password() {
    # 设置密码长度
    local LENGTH=14
    # 定义可用字符集
    local CHARS='abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()-_=+'
    # 生成密码
    local PASSWORD=''
    for ((i=0; i<$LENGTH; i++)); do
        # 随机选择一个字符
        local CHAR=${CHARS:$((RANDOM % ${#CHARS})):1}
        PASSWORD+=$CHAR
    done
    # 返回生成的密码
    echo "$PASSWORD"
}

#######################定义变量##############################
# 配置文件
seeds_ip1=10.172.0.50
seeds_ip2=10.172.0.50
seeds_ip3=10.172.0.50

# 端口
PORT=4306
# mysql部署好后root的默认密码（压测时为123456）

my_root_passwd=$(generate_mysql_password)
my_replication_passwd=rpl_user_yxjk2022
# mysql版本
echo "安装前请检查磁盘是否已完成挂载 fdisk -l"
read -p "请输入数字选择mysql版本（1:8.0.33,2:8.0.20;3:5.7.44,4:5.7.38）：" -e install_version
if [ "$install_version" = "1" ];then
    mysql_version=8.0.33
elif [ "$install_version" = "2" ];then
    mysql_version=8.0.20
elif [ "$install_version" = "3" ];then
    mysql_version=5.7.44
elif [ "$install_version" = "4" ];then
    mysql_version=5.7.38
else
    echo_error 请输入正确的数字
    exit 99
fi
current_step=1
# 部署目录的父目录
cd /usr/local
DIR=$(pwd)

# 部署目录的名字最终的部署目录为${DIR}/${mysql_dir_name}
mysql_dir_name=mysql-${mysql_version}
# mysql二进制包名字
if [ "$mysql_version" = "5.7.38" ];then
    mysql_tgz=mysql-${mysql_version}-linux-glibc2.12-x86_64.tar.gz
fi
if [ "$mysql_version" = "5.7.38" ];then
    mysql_tgz=mysql-${mysql_version}-linux-glibc2.12-x86_64.tar.gz
fi
if [ "$mysql_version" = "5.6.51" ];then
    mysql_tgz=mysql-${mysql_version}-linux-glibc2.12-x86_64.tar.gz
fi
if [ "$mysql_version" = "8.0.20" ];then
    mysql_tgz=mysql-${mysql_version}-linux-glibc2.12-x86_64.tar.xz
fi
if [ "$mysql_version" = "8.0.33" ];then
    mysql_tgz=mysql-${mysql_version}-linux-glibc2.12-x86_64.tar.xz
fi
cloud_platform=n
current_step=1

# 检查/usr/local下是否有mysql_tgz文件
if [ -f /usr/local/${mysql_tgz} ];then
    echo_warning 检测到mysql二进进包${mysql_tgz}已存在无需下载
else
    echo_info ${current_step} "下载mysql二进进包"
    wget 'https://jaken150-1255922873.cos.ap-nanjing.myqcloud.com/'${mysql_tgz}
    ((current_step++))
fi
#######################定义变量##############################


function gen_my_cnf() {
    my_cnf_file=/etc/my.cnf
    echo_info ${current_step} 配置$my_cnf_file
    ((current_step++))
    if [ -f $my_cnf_file ];then
        mv $my_cnf_file ${my_cnf_file}_`date +%Y.%m.%d-%T`
        echo_warning 检测到配置文件已备份为${my_cnf_file}_`date +%Y.%m.%d-%T`
    fi
    # 获取 ens33 网卡的 IP 地址
    ip_address=$(ifconfig | awk '/inet / {print $2}' | sed -n '1p')
    echo_info $ip_address
    # 将$ip_address最后3位改为%
    # 生成新的配置文件
cat > ${my_cnf_file} << EOF
# http://dev.mysql.com/doc/refman/5.7/en/server-configuration-defaults.html
# https://gitee.com/GreatSQL/GreatSQL-Doc/blob/master/docs/my.cnf-example-greatsql-5.7.36#
# GreatSQL -> mysql
# port = ${PORT}
# basedir = ${DIR}/${mysql_dir_name}
# server_id = ${server_id}
# my.cnf

[client]
socket = /data/mysql/mysql.sock
user = root
password = ${my_root_passwd}
[mysql]
prompt="[\\u@${ip_address}] [\\d]>"
[mysqld]
user    = mysql
port = ${PORT}
loose-default-authentication-plugin = mysql_native_password
server_id = ${server_id}
#安装目录
basedir = ${DIR}/${mysql_dir_name}
#数据目录
datadir = /data/mysql
socket = /data/mysql/mysql.sock
#表名和数据库名是不区分大小写的（8.0后果需要在初始化指定，后续不能再修改）
lower_case_table_names = 1
pid-file = mysql.pid
character-set-server = UTF8MB4
#防止DNS欺骗攻击，但chost_cache将不记录数据，无法对访问IP进行block
skip_name_resolve
#若你的MySQL数据库主要运行在境外，请务必根据实际情况调整本参数
default_time_zone = "+8:00"
#内网访问，不开户ssl
skip-ssl

#performance setttings
lock_wait_timeout = 3600
open_files_limit = 65535
back_log = 1024
max_connections = 1024
max_connect_errors = 1000000
table_open_cache = 2048
table_definition_cache = 2048
thread_stack = 512K
sort_buffer_size = 4M
join_buffer_size = 4M
read_buffer_size = 8M
read_rnd_buffer_size = 4M
bulk_insert_buffer_size = 64M
thread_cache_size = 768
interactive_timeout = 600
wait_timeout = 600
tmp_table_size = 96M
max_heap_table_size = 96M
max_allowed_packet = 64M
#GIPK
loose-sql_generate_invisible_primary_key = ON
#配合sysbench压测需要调整此值
max_prepared_stmt_count = 100000

#log settings
log_timestamps = SYSTEM
log_error = /data/mysql/error.log
# 5.7以上需要
loose-log_timestamps = SYSTEM
loose-log_error_verbosity = 3

slow_query_log = 1
slow_query_log_file = /data/mysql/slow.log
long_query_time = 1
log_queries_not_using_indexes = 1
log_throttle_queries_not_using_indexes = 60
min_examined_row_limit = 100
log_slow_admin_statements = 1
log_slow_slave_statements = 1
log_bin = /data/mysql/mysql-bin.log
binlog_format = ROW
sync_binlog = 1
binlog_cache_size = 4M
max_binlog_cache_size = 2G
max_binlog_size = 1G
binlog_rows_query_log_events = 1
#MySQL 8.0.22前，想启用MGR的话，需要设置binlog_checksum=NONE才行
binlog_checksum = NONE
gtid_mode = ON
enforce_gtid_consistency = TRUE
log_slave_updates = 1
expire_logs_days = 7

#myisam settings
key_buffer_size = 32M
myisam_sort_buffer_size = 128M

#replication settings
master_info_repository = TABLE
relay_log_info_repository = TABLE
relay_log_recovery = 1
# 5.7以上需要
loose-slave_parallel_type = LOGICAL_CLOCK
#可以设置为逻辑CPU数量的2倍
loose-slave_parallel_workers = 8
loose-binlog_transaction_dependency_tracking = WRITESET
loose-transaction_write_set_extraction = XXHASH64
loose-slave_preserve_commit_order = 1
loose-slave_checkpoint_period = 2

#innodb settings
innodb_buffer_pool_size = ${innodb_buffer_pool_size}M
innodb_buffer_pool_instances = 8
innodb_data_file_path = ibdata1:12M:autoextend
innodb_flush_log_at_trx_commit = 1
innodb_log_buffer_size = 32M
innodb_log_file_size = 2G
innodb_log_files_in_group = 3
innodb_io_capacity = 4000
innodb_io_capacity_max = 8000
innodb_open_files = 65534
innodb_flush_method = O_DIRECT
innodb_lru_scan_depth = 4000
innodb_lock_wait_timeout = 10
innodb_rollback_on_timeout = 1
innodb_print_all_deadlocks = 1
innodb_status_file = 1
innodb_adaptive_hash_index = 0
innodb_numa_interleave = OFF

EOF

    # 判断install_mode
    if [ "$install_mode" = "1" ];then
        echo_info ${current_step} "MGR配置"
        ((current_step++))
        cat > ${my_cnf_file} << EOF
#mgr settings
loose-plugin_load_add = 'group_replication.so'
# 8.0.20以上版本需要加载clone.so插件
loose-plugin_load_add = 'mysql_clone.so'
loose-group_replication_group_name = "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaa1"
#MGR本地节点IP:PORT，请自行替换
loose-group_replication_local_address = "${ip_address}:${PORT}1"
#MGR集群所有节点IP:PORT，请自行替换
loose-group_replication_group_seeds = '${seeds_ip1}:${PORT}1,${seeds_ip2}:${PORT}1,${seeds_ip3}:${PORT}1'
loose-group_replication_start_on_boot = OFF
loose-group_replication_bootstrap_group = OFF
loose-group_replication_exit_state_action = READ_ONLY
loose-group_replication_flow_control_mode = "DISABLED"
loose-group_replication_single_primary_mode = ON
loose-group_replication_request_time_threshold = 0 #当怀疑MGR成为性能瓶颈时再开启，例如设置为50000(50ms)
report-host = ${ip_address}
report_port = ${PORT}
EOF
    elif [ "$install_mode" = "2" ]; then
        echo_info ${current_step} "主从: 半同步复制中的无损复制"
        cat >> ${my_cnf_file} << EOF
#插件目录
plugin_dir = ${DIR}/${mysql_dir_name}/lib/plugin
EOF
        if [ "$server_id" = "1" ];then
            cat >> ${my_cnf_file} << EOF
plugin-load-add = rpl_semi_sync_master=semisync_master.so
loose-rpl_semi_sync_master_enabled = ON
# 半同步复制中的无损复制
loose-rpl_semi_sync_master_wait_point = AFTER_SYNC
EOF
        else
            cat >> ${my_cnf_file} << EOF
plugin-load-add = rpl_semi_sync_master=semisync_slave.so
loose-rpl_semi_sync_slave_enabled = ON
EOF
        fi
    fi
}


# 脚本执行用户检测
if [[ $(whoami) != 'root' ]];then
    echo_error 请使用root用户执行
    exit 99
fi

# 检测操作系统
if [[ -e /etc/centos-release ]]; then
	os="centos"
	os_version=$(grep -oE '[0-9]+\.?.*\s' /etc/centos-release)
else
	echo_error 不支持的操作系统
	exit 99
fi

unit_file_name=mysqld.service

#############################################################

# 解压
function untar_tgz(){
    echo_info ${current_step} 解压 $1 中
    ((current_step++))
    tar xf $1
    if [ $? -ne 0 ];then
        echo_error 解压出错 请检查
        exit 80
    fi
}

function pre_install(){
    echo_info ${current_step} 安装依赖
    ((current_step++))

    if [ "$cloud_platform" = "t" ];then
        echo_info "腾讯云服务器安装依赖"
        # 检查并安装依赖包
        packages=("numactl")
        for package in "${packages[@]}"
        do
            if ! rpm -q "$package" > /dev/null 2>&1; then
                echo_info "安装依赖包: $package"
                yum -y install "$package"
            else
                echo_info "依赖包 $package 已经安装"
            fi
        done
    fi

    # 检查并安装依赖包
#    packages=("numactl" "libaio" "libaio-devel" "perl-Data-Dumper" "perl-JSON" "dstat")
    packages=("libaio")
    for package in "${packages[@]}"
    do
        if ! rpm -q "$package" > /dev/null 2>&1; then
            echo_info "安装依赖包: $package"
            yum -y install "$package"
        else
            echo_info "依赖包 $package 已经安装"
        fi
    done
}

function add_user_and_group(){
    echo_info ${current_step} 添加用户和组
    ((current_step++))
    if id -g ${1} >/dev/null 2>&1; then
        echo_warning ${1}组已存在无需创建
    else
        groupadd ${1}
        echo_info 创建${1}组
    fi
    if id -u ${1} >/dev/null 2>&1; then
        echo_warning ${1}用户已存在无需创建
    else
        useradd -M -g ${1} -s /sbin/nologin ${1}
        echo_info 创建${1}用户
    fi
    # 数据目录为mysql:mysql
    echo_info ${current_step} 创建数据目录/日志目录
    ((current_step++))
    mkdir -p /data/mysql
    chown -R mysql:mysql /data/mysql
    chown -R mysql:mysql ${DIR}/${mysql_dir_name}/

}


function mgr_change_master_to() {
    echo_info ${current_step} "mgr slave 连接集群"
    ((current_step++))
    # CHANGE MASTER TO MASTER_USER='rpl_user', MASTER_PASSWORD='2222AAaa_' FOR CHANNEL 'group_replication_recovery';
    mysql -uroot -p"${my_root_passwd}" -e " CHANGE MASTER TO MASTER_USER=‘rpl_user’, MASTER_PASSWORD=‘2222AAaa_’ FOR CHANNEL 'group_replication_recovery';" &> /dev/null
    mysql -uroot -p"${my_root_passwd}" -e "START GROUP_REPLICATION;" &> /dev/null
}


function change_master_to(){
    read -p "请输入master服务器IP：" -e master_ip
    read -p "请输入master服务器Port：" -e master_port
    echo_info ${current_step} "从节点上CHANGE MASTER TO"
    ((current_step++))
    # CHANGE MASTER TO MASTER_HOST='192.168.35.135', MASTER_PORT=4306, MASTER_USER='replication', MASTER_PASSWORD='2222AAaa_', master_auto_position=1;
    mysql -uroot -p"${my_root_passwd}" -e "CHANGE MASTER TO MASTER_HOST='${master_ip}', MASTER_PORT=${master_port}, MASTER_USER='rpl_user', MASTER_PASSWORD='${my_replication_passwd}', master_auto_position=1;" &> /dev/null
    mysql -uroot -p"${my_root_passwd}" -e "START SLAVE;" &> /dev/null
    }


function init_account(){
    login_pass=$1
    echo_info ${current_step} systemctl启动mysql
    ((current_step++))
    systemctl enable ${unit_file_name} >/dev/null 2>&1
    systemctl start ${unit_file_name}
    # mysql启动失败的话退出
    if [ $? -ne 0 ];then
        echo_error mysql启动失败请查看错误信息
        exit 81
    fi

    # mysql启动成功后的操作
    source /etc/profile

    echo_info ${current_step} 设置密码
    ((current_step++))


    if [ "$mysql_version" = "5.6.51" ];then
        mysql -uroot  "GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY '${my_root_passwd}' WITH GRANT OPTION;" &> /dev/null
    elif [ "$mysql_version" = "5.7.44" ]; then
        mysql -uroot -p"${login_pass}" --connect-expired-password -e "SET PASSWORD = PASSWORD('${my_root_passwd}');" &> /dev/null
    else
        mysql -uroot -p"${login_pass}" --connect-expired-password -e "ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '${my_root_passwd}';;" &> /dev/null
    fi

    # replication slave用户创建
    echo_info ${current_step} rpl_user/pmm/umpmonitor用户创建
        ((current_step++))
    # set session sql_log_bin=0; create user 'rpl_user'@'%' identified WITH mysql_native_password by '2222AAaa_'; set session sql_log_bin=1;
    rpl_user_ip_address=${ip_address%.*}.%
    echo "rpl_user_ip_address:${rpl_user_ip_address}"
    mysql -uroot -p"${my_root_passwd}" -e "set session sql_log_bin=0; create user 'rpl_user'@'${rpl_user_ip_address}' identified WITH mysql_native_password by '${my_replication_passwd}'; set session sql_log_bin=1;" &> /dev/null
    mysql -uroot -p"${my_root_passwd}" -e "set session sql_log_bin=0; grant replication slave on *.* to 'rpl_user'@'${rpl_user_ip_address}'; set session sql_log_bin=1;" &> /dev/null
    # 创建umpmonitor和pmm账号和密码
    mysql -uroot -p"${my_root_passwd}" -e "set session sql_log_bin=0; create user 'umpmonitor'@'100.168.132.%' identified WITH mysql_native_password by 'Monitor_yxjk2022'; set session sql_log_bin=1;" &> /dev/null
    mysql -uroot -p"${my_root_passwd}" -e "set session sql_log_bin=0; grant select,execute,process,replication client,usage,show databases,show view on *.* to 'umpmonitor'@'100.168.132.%'; set session sql_log_bin=1;" &> /dev/null

    # todo 'pmm'@'%'
    mysql -uroot -p"${my_root_passwd}" -e "set session sql_log_bin=0; create user 'pmm'@'%' identified WITH mysql_native_password by 'Monitor_yxjk2022'; set session sql_log_bin=1;" &> /dev/null
    mysql -uroot -p"${my_root_passwd}" -e "set session sql_log_bin=0; GRANT SELECT, PROCESS, REPLICATION CLIENT, RELOAD, BACKUP_ADMIN on *.* to 'pmm'@'%'; set session sql_log_bin=1;" &> /dev/null
    mysql -uroot -p"${my_root_passwd}" -e "reset master;" &> /dev/null

#    if [ "$server_id" = "1" ];then
#      echo_info ${current_step} 仅在主节点上创建备份用户replication
#      ((current_step++))
#      # create user 'replication'@'%' identified WITH mysql_native_password by '2222AAaa_';
#      mysql -uroot -p"${my_root_passwd}" -e "create user 'replication'@'%' identified WITH mysql_native_password by '${my_replication_passwd}';" &> /dev/null
#      mysql -uroot -p"${my_root_passwd}" -e "grant replication slave on *.* to 'replication'@'%';" &> /dev/null
#      mysql -uroot -p"${my_root_passwd}" -e "reset master;" &> /dev/null
#
#    fi
    if [ "$install_mode" = "2" ];then
      if [ "$server_id" = "2" ];then
        change_master_to
      fi
    fi

    echo_info ${current_step} 验证mysql重启功能
    ((current_step++))
    systemctl restart ${unit_file_name}


    echo_info mysql已启动成功相关信息如下
    echo -e "\033[37m                  端口：${PORT}\033[0m"
    echo -e "\033[37m                  账号：root\033[0m"
    echo -e "\033[37m                  密码：${my_root_passwd}\033[0m"

    echo_info mysql控制命令
    echo -e "\033[37m                  启动：systemctl start ${unit_file_name}\033[0m"
    echo -e "\033[37m                  重启：systemctl restart ${unit_file_name}\033[0m"
    echo -e "\033[37m                  停止：systemctl stop ${unit_file_name}\033[0m"
}


function check_dir() {
    if [ -d $1 ];then
        echo_error 目录 $1 已存在退出
        exit 83
    fi
}

function install_by_tgz(){
    ps -ef | grep "${DIR}/${mysql_dir_name}" | grep -v grep &> /dev/null
        if [ $? -eq 0 ];then
            echo_error 检测到mysql正在运行中退出
            exit 86
        fi

        if [ -d ${DIR}/${mysql_dir_name} ];then
            echo_warning 检测到目录${DIR}/${mysql_dir_name}请检查是否重复安装退出
            read -p "是否继续安装(y/n):" -e is_continue
            if [ "$is_continue" = "n" ];then
                exit 87
            fi
        else
          untar_tgz ${mysql_tgz}
          mv mysql-${mysql_version}-linux-glibc2.12-x86_64 ${DIR}/${mysql_dir_name}
        fi
    pre_install
    add_user_and_group mysql
    gen_my_cnf
    #　debug结束安装
#    if [ "$install_mode" = "2" ];then
#        exit
#    fi
    echo_info ${current_step} 初始化mysql
    ((current_step++))
    # 初始化
    cd /data/mysql
    # 5.7以上
    if [ "$mysql_version" = "5.6.51" ];then
        ${DIR}/${mysql_dir_name}/scripts/mysql_install_db --user=mysql --basedir=${DIR}/${mysql_dir_name} --datadir=/data/mysql &> /dev/null
    else
        ${DIR}/${mysql_dir_name}/bin/mysqld --initialize --user=mysql &> /dev/null
    fi
    # 获取初始密码
#    init_password=$(awk '/password/ {print $11}' /data/mysql/error.log)
    init_password=$(awk '/temporary password/ {print $NF}' /data/mysql/error.log)
    echo_info 初始密码为：${init_password} 初始化完毕
    if [ -z $init_password ];then
        echo_error 初始化失败请查看日志
        exit 82
    fi


    # 设置systemctl控制
    echo_info ${current_step} 生成${unit_file_name}文件用于systemd控制
    ((current_step++))

cat > /lib/systemd/system/${unit_file_name} << EOF
[Unit]
Description=mysql
After=network.target
[Service]
LimitNPROC=65535
LimitNOFILE=65535
User=mysql
Group=mysql
Type=forking
ExecStart=${DIR}/${mysql_dir_name}/support-files/mysql.server start
ExecStop=${DIR}/${mysql_dir_name}/support-files/mysql.server stop
ExecReload=${DIR}/${mysql_dir_name}/support-files/mysql.server reload
PrivateTmp=true
Restart=always
[Install]
WantedBy=multi-user.target
EOF

    # 添加环境变量这样就能在任意地方使用mysql全套命令
    echo_info ${current_step} 配置PATH环境变量
    ((current_step++))
    if [ -f /usr/local/bin/mysql ];then
        echo_error /usr/local/bin目录有未删除的mysql相关文件请检查
        exit 84
    fi
    if [ -f /usr/bin/mysql ];then
        echo_error /usr/bin目录有未删除的mysql相关文件请检查
        exit 85
    fi
    echo "export PATH=\${PATH}:${DIR}/${mysql_dir_name}/bin" > /etc/profile.d/mysql.sh
    source /etc/profile

    # 进行账号、密码设置
    init_account ${init_password}

    echo_info 由于bash特性限制在本终端连接mysql需要先手动执行 source /etc/profile 加载环境变量或者新开一个终端连接mysql
    echo_info 集群安装请手动修改/etc/my.cnf中的group_replication_group_seedsIP地址
}


function install_main_func(){
    read -p "请输入数字选择操作类型（如需退出请输入q）：" -e install_mode

    if [[ $os == 'centos' ]];then
        case $install_mode in
            1|2)
                read -p "请输节点ID（主节点请输入1；备节点请输入2）：" -e server_id
                read -p "如果是腾讯云服务器请输入t，其余直接回车：" -e cloud_platform
                install_by_tgz
                ;;
            q|Q)
                exit 0
                ;;
            *)
                install_main_func
                ;;
        esac
    fi
}

# 获取内存总大小（单位：KB）
total_memory=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
# 转换为MB
total_memory_mb=$(expr $total_memory / 1024 )

# innodb_buffer_pool_size设置为total_memory_mb的0.75,取整数
innodb_buffer_pool_size=$(expr $total_memory_mb \* 3 / 5)

echo "总内存 (MB): $total_memory_mb"
echo -e "innodb_buffer_pool_size: $innodb_buffer_pool_size MB"
echo "如需要调整，请自行修改/etc/my.cnf文件"

echo -e "\033[31m本脚本仅Centos7+支持二进制包部署方式\033[0m"
echo -e " 1、安装：MGR集群"
echo -e " 2、安装：1主1从"
install_main_func